const Router = require('koa-router')
const router = new Router()
const rp = require('request-promise')
const tools = require('../../servse/tools')
const debug = require('debug')('print')
const db = require('../../servse/db.js')
const qr = require('qr-image')
const ConfigManager = require('../../lib/config.js')
const jwt = require('jsonwebtoken')
const UUid = require('uuid')
// const logger = require('../../lib/logger')
const { accessLogger, logger } = require('../../lib/logger')

/**
 * @router POST api/print/qr_image
 * @desc   生成二维码接口
 * @access 接口共有
 */
router.get('/qr_image', async (ctx, next) => {
  const text = ctx.query.text
  // console.log(text)
  try {
    const img = await qr.image(text, { size: 10 })
    ctx.type = 'image/png'
    ctx.body = img
    // 执行该办法会在项目目录中生成对应的二维码图片，
    // img.pipe(require('fs').createWriteStream('qr-Q.png').on('finish', function () {
    //   console.log('write finished')
    // }))
  } catch (e) {
    logger.error('生成二维码错误:', e)
    ctx.body.writeHead(414, { 'Content-Type': 'text/html' })
    ctx.body.end('<h1>414 Request-URI Too Large</h1>')
  }
})

/**
 * @router GET api/print/getprint
 * @desc 扫描识别打印机
 * @access 接口共有
 */
router.get('/getprint/:printerUuid', async (ctx, next) => {
  const token = ctx.headers.authorization
  const printerUuid = ctx.params.printerUuid
  if (token) {
    await jwt.verify(token, ConfigManager.getSecretKey(), async (err, decoded) => {
      if (err) {
        ctx.status = 400
        ctx.body = {
          errcode: 1,
          errmsg: err
        }
        return ctx.body
      } else {
        const results = await db.findPrintId(printerUuid)
        const result = results[0]
        ctx.status = 200
        ctx.body = {
          errcode: 0,
          data: { result }
        }
        return ctx.body
      }
    })
  }
})

/**
 * @router POST api/print/prints
 * @desc 控制打印机
 * @access 接口共有
 */
router.post('/prints', async (ctx, next) => {
  const token = ctx.headers.authorization
  if (token) {
    await jwt.verify(token, ConfigManager.getSecretKey(), async (err, decoded) => {
      if (err) {
        ctx.status = 400
        ctx.body = {
          errcode: 1,
          errmsg: err
        }
        return ctx.body
      } else {
        const fileUuid = ctx.request.body.fileUuid
        const printerUuid = ctx.request.body.printerUuid
        const jobUuid = UUid.v4()
        const fileName = await db.findFilestat(fileUuid)
        const printer = await db.findPrintId(printerUuid)
        debug('jobUuid: %s, pdf file: %s, printer: %s', jobUuid, fileName[0].fileName, printer[0].printerUuid)
        // console.log(`${ctx.origin}/pdf/` + fileUuid + '.pdf')
        const options = tools.print(jobUuid, fileName[0].fileUuid, printer[0].bid, printer[0].deviceid)
        const result = await rp(options)
        debug('网蛙请求参数：%s, 打印结果回调: %s', options, result)
        // 打印记录
        await db.savaRecord(jobUuid, decoded.id, decoded.name, fileName[0].fileName, 'undone')
        ctx.body = {
          err: 0,
          data: {
            jobUuid: jobUuid
          }
        }
        return ctx.body
      }
    })
  }
})

/**
 * @router POST api/print/printStatus
 * @desc 打印监听接口_监听网蛙中心
 * @access 接口共有
 */
router.post('/printStatus', async (ctx, next) => {
  debug('监听网蛙中心jobid：', ctx.request.body.msgId)
  debug('监听网蛙中心返回打印结果：', ctx.request.body.status)
  const jobUuid = ctx.request.body.msgId
  if (ctx.request.body.status === 'done') {
    const result = await db.findRecord(jobUuid)
    // 修改打印记录结果
    await db.updateRecord(jobUuid, 'finish')
    // 用户打印次数加一
    await db.AddUserPrintNumber(result[0].userId)
    ctx.body = {
      errcode: 0,
      errmsg: 'success'
    }
    return ctx.body
  } else {
    // 修改打印记录结果
    await db.updateRecord(jobUuid, 'fail')
    ctx.body = {
      errcode: 0,
      errmsg: 'success'
    }
    return ctx.body
  }
})

/**
 * @router POST api/print/printStatus
 * @desc 打印监听接口_监听小程序端
 * @access 接口共有
 */
router.get('/printStatus/:jobUuid', async (ctx, next) => {
  // console.log(ctx.params.jobUuid)
  const jobUuid = ctx.params.jobUuid
  const result = await db.findRecord(jobUuid)
  if (result[0].status === 'finish') {
    ctx.status = 200
    ctx.body = {
      errcode: 0,
      data: {
        status: 'done'
      }
    }
    return ctx.body
  } else if (result[0].status === 'undone') {
    ctx.status = 200
    ctx.body = {
      errcode: 0,
      data: {
        status: 'commit'
      }
    }
    return ctx.body
  } else {
    ctx.status = 200
    ctx.body = {
      errcode: 0,
      data: {
        status: 'error'
      }
    }
    return ctx.body
  }
})

/**
 * @router GET api/print/proFile
 * @desc 获取用户打印次数
 * @access 接口共有
 */
router.get('/proFile', async (ctx, next) => {
  const token = ctx.headers.authorization
  if (token) {
    await jwt.verify(token, ConfigManager.getSecretKey(), async (err, decoded) => {
      if (err) {
        ctx.status = 400
        ctx.body = {
          errcode: 1,
          errmsg: err
        }
        return ctx.body
      } else {
        const userId = decoded.id
        const result = await db.findUserId(userId)
        ctx.status = 200
        ctx.body = {
          errcode: 0,
          data: {
            printCount: result[0].printNumber
          }
        }
        return ctx.body
      }
    })
  }
})

module.exports = router.routes()
